package com.secondkill.service;

import com.secondkill.dao.MiaoshaUserMapper;
import com.secondkill.entity.MiaoshaUser;
import com.secondkill.exception.GlobalException;
import com.secondkill.redis.MiaoshaUserKey;
import com.secondkill.redis.RedisKeyPrefix;
import com.secondkill.redis.RedisService;
import com.secondkill.result.CodeMsg;
import com.secondkill.utils.Md5Utils;
import com.secondkill.utils.UUIDUtil;
import com.secondkill.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IBM on 2018/7/5.
 */
@Service
public class MiaoshaUserService {


    public static final String COOKI_NAME_TOKEN = "token";
    @Autowired
    MiaoshaUserMapper miaoshaUserMapper;
    @Autowired
    RedisService redisService;

    public Boolean doLogin(HttpServletResponse response, LoginVo loginVo) {

        String mobile = loginVo.getMobile();
        if (StringUtils.isBlank(mobile)) {
            throw new GlobalException(CodeMsg.MOBILE_EMPTY);
        }
        MiaoshaUser byId = miaoshaUserMapper.getById(Long.parseLong(mobile));
        if (byId == null ){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        String serverSalt = byId.getSalt();
        String dbPass = byId.getPassword();
        String formPass = loginVo.getPassword();
        String validPass = Md5Utils.formPassToDbPass(formPass, serverSalt);
        System.out.println("comes to valid");
        if (StringUtils.equals(dbPass, validPass)) {
            System.out.println("valid true");
            MiaoshaUserKey miaoshaUserKey = MiaoshaUserKey.token;
            String uuid = UUIDUtil.uuid();
            addCookie(response, byId, miaoshaUserKey, uuid);
            return true;
        } else {
            throw new GlobalException(CodeMsg.MOBILE_ERROR);
        }


    }

    private void addCookie(HttpServletResponse response, MiaoshaUser byId, MiaoshaUserKey miaoshaUserKey, String uuid) {
        redisService.set(miaoshaUserKey, uuid, byId);

        Cookie cookie = new Cookie(COOKI_NAME_TOKEN, uuid);
        cookie.setMaxAge(miaoshaUserKey.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    public MiaoshaUser getByToken(HttpServletResponse response, String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        //延长有效期
        if(user != null) {
            addCookie(response, user, MiaoshaUserKey.token, token);
        }
        return user;
    }
}
